package com.akk.platform.oem.business;

import com.akk.module.avs.entity.AvsYbBank;
import com.akk.module.avs.model.request.AvsYbBankRequest;
import com.akk.module.avs.service.AvsYbBankService;
import com.akk.module.upload.service.PictureService;
import com.akk.utils.PageUtils;
import com.akk.utils.Query;
import com.akk.utils.RestResponse;
import com.akk.utils.ShiroUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

import java.util.List;
import java.util.Map;

@Component
public class YbBankBusiness {

    @Autowired
    private AvsYbBankService bankService;

    @Autowired
    private PictureService pictureService;

    public RestResponse list(Query query, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return RestResponse.build("1", bindingResult.getFieldError().getDefaultMessage());
        PageHelper.startPage(query.getPage(), query.getLimit());
        Map params = query.getSearch();
        params.put("appId", ShiroUtils.getAdmin().getAppId());
        List<AvsYbBank> list = bankService.queryByParams(params);
        return RestResponse.build(PageUtils.buildPage(list, (int) new PageInfo<>(list).getTotal(), query));
    }

    public RestResponse save(AvsYbBankRequest request,BindingResult bindingResult){
        if (bindingResult.hasErrors())
            return RestResponse.build("1", bindingResult.getFieldError().getDefaultMessage());
        Map result = pictureService.uploadPicture(request.getIcon());
        if (result.get("status").toString().equals("1"))
            return RestResponse.build("1","文件上传失败");
        request.setBankIcon(result.get("url").toString());
        request.setAppId(ShiroUtils.getAdmin().getAppId());
        bankService.save(request);
        return RestResponse.build("success");
    }

    public RestResponse del(Long bankId){
        AvsYbBank bank = bankService.queryById(bankId);
        if (StringUtils.isEmpty(bank.getBankIcon()) && bank.getBankIcon().length() > 8)
            pictureService.removeFile(bank.getBankIcon());
        bankService.del(bankId);
        return RestResponse.build("success");
    }

}
